package com.hugoo.form.buzz;

import com.hugoo.core.cip.LxCipher;
import com.hugoo.core.util.TL;
import com.hugoo.form.xo.XHandle;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 * @author Lovelock.Chan
 */
public class CacheProc {

    private static final Map<String, CacheData> m = new ConcurrentHashMap<String, CacheData>(200, 0.95f);

    public static String getCacheKeys(XHandle sid, Map para) {
        StringBuilder sb = new StringBuilder();
        sb.append(sid.getxForm().getId()).append("-").append(sid.getId()).append("?");
        String rst = sid.getChkey();
        String[] k = rst.split(",");
        for (String x : k) {
            sb.append("&").append(x).append("=").append(para.get(x.toUpperCase()));
        }
        return LxCipher.MD5(sb.toString());
    }

    public static String getCacheKeys(String sid, String prg, Map para) {
        StringBuilder sb = new StringBuilder();
        sb.append(sid).append("-").append("json?");
        if (!TL.isEmpty(prg)) {
            String pg[] = prg.split(",");
            for (String p : pg) {
                sb.append(p).append("=").append(para.get(p));
            }
        }
        return LxCipher.MD5(sb.toString());
    }

    public static void clearCacheData() {
        if (m != null && !m.isEmpty()) {
            m.clear();
        }
    }

    public static boolean haveCacheData(String key) {
        return m.containsKey(key);
    }

    public static String cacheData(String key) {
        return m.get(key).getData();
    }

    public static void cacheData(String key, String data) {
        m.put(key, new CacheData(data));
    }

    public static String listCacheData() {
        return m.toString();
    }

    static class CacheData {

        final String data;
        final long cTime = System.currentTimeMillis();
        long count = 0;
        long lstTime = cTime;

        public CacheData(String data) {
            this.data = data;
        }

        public String getData() {
            count++;
            lstTime = System.currentTimeMillis();
            return data;
        }

        @Override
        public String toString() {
            return "CacheData{" + "cTime=" + cTime + ", count=" + count + ", lstTime=" + lstTime + '}';
        }
    }
}
